import { Component, Vue } from 'vue-property-decorator'
import store from '@/store/index'
import { ICommon } from '@/units/common'
import { IClientVm, IConfig } from '@/interface/common'
import { Log, ILogger } from '@/units/logger'
import { ICardReader } from '@/units/reader'
declare let Common: ICommon
declare let IdCardReader: ICardReader
declare let IcCardReader: ICardReader

@Component({
  name: 'BaseMixin'
})
export default class BaseMixin extends Vue {
  protected store = store
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  protected client : IClientVm = {}
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  protected config : IConfig = {}
  protected logger : ILogger = Log
  protected common : ICommon = Common
  protected idCardReader : ICardReader = IdCardReader
  protected icCardReader : ICardReader = IcCardReader
  protected handlers :number[] = []

  // 显示加载窗口
  protected showLoading (title = '加载中') : void {
    store.commit('showLoading', title)
  }

  // 关闭加载窗口
  protected hideLoading () : void {
    store.commit('hideLoading')
  }

  // 导航
  protected navigateTo (path: string) : void{
    this.$router.push(path)
  }

  protected clear () :void{
    this.clearTimeout()
    this.setMaxTime(0)
    this.setTip('')
    this.store.commit('updatePersonalInfo', undefined)
    this.store.state.bizType = undefined
    this.store.state.cardType = undefined
  }

  // 返回
  protected back () : void{
    if (this.$route.path === `/${this.getRoute()}/home`) {
      window.location.reload()
    } else {
      this.clear()
      this.$router.back()
    }
  }

  protected home () : void{
    this.clear()
    this.$router.replace('/')
  }

  // 设置返回时间
  protected setTime (time: number) : void{
    store.commit('updateTime', time)
  }

  // 设置返回时间
  protected setMaxTime (time: number) : void{
    store.commit('updateTime', time)
    store.commit('updateMaxTime', time)
  }

  // 设置消息提示
  protected setTip (tip: string): void{
    store.commit('updateTip', tip)
  }

  // 倒计时
  protected updateTimeHandler (action: 'back' | 'home') :void {
    if (this.store.state.time > 0) {
      const handler = setTimeout(() => {
        this.setTime(this.store.state.time - 1)
        this.updateTimeHandler(action)
      }, 1000)
      this.handlers.push(handler)
    } else {
      switch (action) {
        case 'back':
          this.back()
          break
        case 'home':
          this.home()
          break
        default:
          break
      }
    }
  }

  protected getRoute () :string {
    return this.store.state.client.Entity.Theme.Route
  }

  protected clearTimeout () : void {
    this.handlers.forEach(element => {
      clearTimeout(element)
    })
  }
}
